<template>
  <view class="address-page">
    <view class="header">
      <view class="title">{{isFromOrder? '选择收货地址' : '管理收货地址'}}</view>
      <view class="new-btn" @click="createNewAddress">新建</view>
    </view>
    <view class="address-list">
      <!-- 如果地址列表为空，显示提示信息 -->
      <view v-if="addresses.length === 0" class="empty-tip">
        <text>暂无收货地址</text>
        <text class="add-tip">点击右上角"新建"添加地址</text>
      </view>
      <!-- 如果地址列表不为空，遍历显示地址项 -->
      <view v-else v-for="(address, index) in addresses" :key="address.id" 
        class="address-item" 
        :class="{'selectable': isFromOrder}"
        @click="selectAddress(address, index)">
        <view class="address-content">
          <view class="contact-info">
            <text class="name">{{address.name}}</text>
            <text class="phone">{{address.phone}}</text>
            <text v-if="address.isDefault" class="default-tag">默认</text>
          </view>
          <view class="address-detail">
            <text>{{address.city}} {{address.department}} {{address.houseNumber}}</text>
          </view>
        </view>
        <view class="item-footer">
          <view class="actions">
            <view class="edit-btn" @click.stop="editAddress(address)">
              <uni-icons type="compose" size="20" color="#666"></uni-icons>
              <text class="btn-text">编辑</text>
            </view>
            <view class="delete-btn" @click.stop="deleteAddress(address)">
              <uni-icons type="trash" size="20" color="#666"></uni-icons>
              <text class="btn-text">删除</text>
            </view>
          </view>
          <view v-if="isFromOrder" class="select-tip" :class="{ 'text-red': address.isSelected }" @click="selectAddress(address, index)">
            <text>使用</text>
            <text class="arrow">›</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
	import config from '@/config'
export default {
  data() {
    return {
      addresses: [],
      userId: '', 
      isFromOrder: false 
    }
  },
  onLoad(options) {
    // 从本地存储中获取用户信息
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      this.userId = JSON.parse(userInfo)._id;
    }
    // 判断是否从订单页跳转过来
    this.isFromOrder = Boolean(options.from === 'order');
    // 加载地址列表
    this.fetchAddresses();
  },
  methods: {
    // 选择地址
    selectAddress(address, index) {
      if (!this.isFromOrder) return;
      
      // 构造选中的地址信息
      const addressInfo = {
        name: address.name,
        phone: address.phone,
        address: `${address.city} ${address.department} ${address.houseNumber}`,
        isDefault: address.isDefault,
        userId: this.userId 
      };
      
      // 假设这里有一个接口来存储选中的地址信息，暂时用console.log模拟
      console.log('选中的地址信息:', addressInfo);
      
      // 显示选择成功提示
      uni.showToast({
        title: '使用成功',
        icon:'success',
        duration: 1500
      });
      
      // 设置当前地址为已选中状态
      this.addresses[index].isSelected = true;
      
      // 取消其他地址的选中状态
      this.addresses.forEach((addr, i) => {
        if (i!== index) {
          addr.isSelected = false;
        }
      });
      
      // 返回上一页
      setTimeout(() => {
        this.addresses.forEach(addr => addr.isSelected = false);
        uni.navigateBack();
      }, 1500);
    },
    // 获取地址列表
    async fetchAddresses() {
      try {
        const response = await uni.request({
          url: config.API+'/address', // 修改为获取所有地址的接口
          method: 'GET'
        });
        if (response.statusCode === 200) {
          this.addresses = response.data;
          // 初始化每个地址的isSelected属性为false
          this.addresses.forEach(addr => addr.isSelected = false);
        } else {
          throw new Error('Failed to fetch addresses');
        }
      } catch (error) {
        uni.showToast({
          title: '获取地址失败',
          icon: 'none'
        });
      }
    },
    // 新建地址
    createNewAddress() {
      uni.navigateTo({
        url: '/pages/me/address-edit'
      });
    },
    // 编辑地址
    editAddress(address) {
      uni.navigateTo({
        url: `/pages/me/address-edit?address=${encodeURIComponent(JSON.stringify(address))}`
      });
    },
    // 删除地址
    async deleteAddress(address) {
      try {
        const res = await uni.showModal({
          title: '提示',
          content: '确定要删除这个地址吗？',
          confirmText: '确定',
          cancelText: '取消'
        });
        
        if (!res.confirm) return;
        
        // 确保有地址ID
        if (!address.id) {
          uni.showToast({
            title: '参数错误',
            icon: 'none'
          });
          return;
        }

        const response = await uni.request({
          url: config.API+`/address/${address.id}`, // 修改为删除地址的接口
          method: 'DELETE'
        });
        
        if (response.statusCode === 200) {
          uni.showToast({
            title: '删除成功',
            icon:'success'
          });
          // 重新获取地址列表
          await this.fetchAddresses();
        } else {
          throw new Error(`删除失败: ${response.statusCode}`);
        }
      } catch (error) {
        console.error('删除地址失败:', error);
        uni.showToast({
          title: error.message || '删除失败',
          icon: 'none',
          duration: 2000
        });
      }
    }
  }
};
</script>

<style>
/* 页面整体样式 */
.address-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx; /* 添加内边距，让页面有一定的留白 */
}

/* 头部样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border-radius: 12rpx; /* 添加圆角 */
  margin-bottom: 20rpx; /* 添加底部外边距 */
}

/* 标题样式 */
.title {
  font-size: 32rpx;
  font-weight: 500;
}

/* 新建按钮样式 */
.new-btn {
  color: #333;
  font-size: 28rpx;
}

/* 地址列表样式 */
.address-list {
  padding: 0; /* 去除内边距 */
}

/* 地址项样式 */
.address-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); 
  transition: box-shadow 0.3s ease; /* 添加过渡效果 */
}

/* 鼠标悬停时地址项样式 */
.address-item:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 悬停时增加阴影 */
}

/* 联系人信息样式 */
.contact-info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

/* 姓名样式 */
.name {
  font-size: 30rpx;
  margin-right: 30rpx;
}

/* 电话样式 */
.phone {
  font-size: 30rpx;
  color: #666;
  margin-right: 20rpx;
}

/* 默认标签样式 */
.default-tag {
  font-size: 24rpx;
  color: #ff6b6b;
  border: 1px solid #ff6b6b;
  padding: 2rpx 10rpx;
  border-radius: 4rpx;
}

/* 地址详情样式 */
.address-detail {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  font-size: 28rpx;
  color: #333;
}

/* 操作按钮组样式 */
.actions {
  display: flex;
  gap: 20rpx;
}

/* 编辑按钮样式 */
.edit-btn,
.delete-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8rpx 12rpx;
  border-radius: 6rpx;
  background-color: #f5f5f5; 
  transition: background-color 0.3s ease; /* 添加过渡效果 */
}

/* 鼠标悬停时编辑按钮样式 */
.edit-btn:hover {
  background-color: #e0e0e0; /* 悬停时改变背景颜色 */
}

/* 鼠标悬停时删除按钮样式 */
.delete-btn:hover {
  background-color: #e0e0e0; /* 悬停时改变背景颜色 */
}

/* 编辑按钮文字颜色 */
.edit-btn {
  color: #007AFF;
}

/* 删除按钮文字颜色 */
.delete-btn {
  color: #FF3B30;
}

/* 按钮文字样式 */
.btn-text {
  font-size: 24rpx;
}

/* 选择提示样式 */
.select-tip {
  font-size: 24rpx;
  color: #666;
}

/* 箭头样式 */
.arrow {
  margin-left: 5px;
}

/* 无地址提示样式 */
.empty-tip {
  padding: 20rpx;
  text-align: center;
  color: #666;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

/* 添加地址提示样式 */
.add-tip {
  font-size: 24rpx;
  margin-top: 10rpx;
}
</style>